<template>
  <a-button
    v-if="props?.data?.isFavorite"
    type="text"
    style="padding: 5px 12px; height: auto; text-align: left"
    @click="cancelFavorites"
    block
  >
    取消收藏
  </a-button>
  <a-button
    v-else
    type="text"
    style="padding: 5px 12px; height: auto; text-align: left"
    @click="favorite"
    block
  >
    收藏
  </a-button>
</template>
<!-- 收藏、取消收藏 -->
<script setup>
import { ref } from 'vue'
import { removeFavorites, addFavorites } from '@/api/favorites.js'
import { useDbType } from '@/views/db-management/provide-context.js'
import { message } from 'ant-design-vue'

/**
 * 外部参数
 */
let props = defineProps({
  data: {
    type: Object,
    required: true,
  },
})
let dbType = useDbType()
/**
 * 事件定义
 */
let emit = defineEmits(['change'])
/**
 * 全局
 */
/**
 * 操作
 */
let loading = ref(false)
// 添加收藏
async function favorite() {
  loading.value = true
  try {
    await addFavorites({ id: props?.data?.dataId }, dbType)
    // await update()
    emit('change')
    loading.value = false
    message.success('收藏成功。')
  } catch (e) {
    loading.value = false
    console.log(e)
  }
  loading.value = false
}
// 取消收藏
async function cancelFavorites() {
  loading.value = true
  try {
    await removeFavorites({ id: props?.data?.dataId }, dbType)
    // await update()
    emit('change')
    message.success('已取消收藏。')
    loading.value = false
  } catch (e) {
    loading.value = false
    console.log(e)
  }
  loading.value = false
}
</script>
<style lang="less" scoped></style>
